'use strict';

const Controller = require('egg').Controller;
const { arrayGroup } = require('../../utils/index')
const {httpFormJson}=require('../../utils/httpUtils')
class HomeApiController extends Controller {
  async showApi() {
    let { ctx, service } = this;
    let parmas = ctx.query;
    let user = ctx.session.user;
    if(!user){
        ctx.redirect('/')
    }else{
    let result = await service.admin.adminApi.apiModel(parmas);
    let groupResult = arrayGroup(result.result)
    await ctx.render('home/homeApi', { result: groupResult, project: result.project,user })
    }
  }

  async showAction(){
    let { ctx, service } = this;
    let parmas = ctx.query;
    let result = await service.admin.adminApi.showApiModel(parmas.api_id)

        if (result !== null) {
            ctx.body = {
                success: true,
                msg: '成功',
                result
            }
        }

  }

  async authApi(){
    let { ctx } = this;
    let params = ctx.request.body;
    let result = await httpFormJson(params.path, JSON.parse(params.parmas), this.ctx.method, '');
    // if(result.body.success){
    let cookie = (result.headers['set-cookie']).toString().split(';')[0]
    ctx.cookies.set('cookie', cookie);
    ctx.body=result.body;
  }

  async clearAuth(){
    let { ctx } = this;
    ctx.cookies.set('cookie', null);
    // ctx.status = 204;
    ctx.body={
      msg:'成功',
      success:true,
    }
  }




  async sendAction() {
    let { ctx, service } = this;
    let params = ctx.request.method === 'POST' ? ctx.request.body : ctx.query;

    let cookie = ctx.cookies.get('cookie');
    let result = await httpFormJson(params.path, JSON.parse(params.parmas), this.ctx.method, cookie);
    if (result == null || result.statusCode === 403) {
      ctx.body={
        success: false,
        msg: '该接口需要授权'
      };
    } else {
      ctx.body=result.body;
    }


  }




}

module.exports = HomeApiController;
